package com.example.lets;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

import com.bmob.BTPFileResponse;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.bmob.btp.callback.UploadListener;
import com.widget.CircleImageView;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MeActivity extends Activity {
	private SelectPicPopupWindow selWindow;
	private Uri                  photoUri = null;
	private String               fileName = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_me);
		Button save = (Button) findViewById(R.id.me_save);
		Button back = (Button) findViewById(R.id.me_back);
		User curUser = (User)BmobUser.getCurrentUser(MeActivity.this,User.class);



		// 将各个输入框的显示值设置为用户当前的信息，删除后会有提示
		EditText nickName = (EditText)findViewById(R.id.me_change_username);
		nickName.setText(curUser.getNickname());
		EditText Tag1 = (EditText)findViewById(R.id.me_change_tag1);
		Tag1.setText(curUser.getTag1());
		EditText Tag2 = (EditText)findViewById(R.id.me_change_tag2);
		Tag2.setText(curUser.getTag2());
		EditText Tag3 = (EditText)findViewById(R.id.me_change_tag3);
		Tag3.setText(curUser.getTag3());

		// 若有头像则下载并显示，否则点击上传头像按钮的事件
		String headFileName = curUser.getPicFilename();
		String name[] = headFileName.split("\\.");
		String newFileName = name[0] + "_2_120_0_100." + name[1];
		String cacheThumbnailPath = BmobPro.getInstance(MeActivity.this).getCacheThumbnailDir() + "/" + newFileName;

		CircleImageView upload = (CircleImageView) findViewById(R.id.me_portrait);

		upload.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) { // 点击打开资源管理器选择图片
				// 实例化SelectPicPopupWindow
				selWindow = new SelectPicPopupWindow(MeActivity.this, new OnClickListener() {
					// 为弹出窗口实现监听类
					public void onClick(View v) {
						selWindow.dismiss();

						int id = v.getId();
						if (id == R.id.btn_take_photo) {

							SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
							String filename = "Lets_Head_" + timeStampFormat.format(new Date());
							ContentValues values = new ContentValues();
							values.put(Media.TITLE, filename);
							Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
							intent1.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
							startActivityForResult(intent1, 1);

						} else if (id == R.id.btn_pick_photo) {

							Intent intent2 = new Intent();
							// 开启Pictures画面Type设定为image
							intent2.setType("image/*");
							// 使用Intent.ACTION_GET_CONTENT这个Action
							intent2.setAction(Intent.ACTION_GET_CONTENT);
							// 取得相片后返回本画面
							startActivityForResult(intent2, 2);

						} else {

							Log.i("bmob", "undefined button");
							Toast.makeText(MeActivity.this, "未定义的按钮！", Toast.LENGTH_SHORT).show();
						}
					}
				});

				// 显示窗口
				// 设置layout在PopupWindow中显示的位置
				selWindow.showAtLocation(findViewById(R.id.me_save),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});

		if (headFileName == null || headFileName == "") { //点击上传头像按钮的事件



		}
		else { // 若有头像则先检查缓存下载并显示

			if ((new File(cacheThumbnailPath)).exists()) {

				Log.i("bmob", "成功加载缓存" + cacheThumbnailPath);
				Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
				CircleImageView cImageView = (CircleImageView) findViewById(R.id.me_portrait);
				cImageView.setImageBitmap(bm); // 将Bitmap设定到CircleImageView

			} else {
				BTPFileResponse response = BmobProFile.getInstance(MeActivity.this).download(headFileName, new DownloadListener() {

					@Override
					public void onSuccess(String fullPath) {
						Log.i("bmob", "下载成功：" + fullPath);
						// 根据下载的图片在本地生成缩略图
						BmobProFile.getInstance(MeActivity.this).getLocalThumbnail(fullPath, 2, new LocalThumbnailListener() {

							@Override
							public void onSuccess(String thumbnailPath) {
								Log.i("bmob", "localThumbnail-->生成后的缩略图路径 :" + thumbnailPath);
								Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
								CircleImageView cImageView = (CircleImageView) findViewById(R.id.me_portrait);
								cImageView.setImageBitmap(bm); // 将Bitmap设定到CircleImageView
							}

							@Override
							public void onError(int statuscode, String errormsg) {
								Log.i("bmob", "localThumbnail-->生成缩略图失败 :" + statuscode + "," + errormsg);
							}
						});
					}

					@Override
					public void onProgress(String localPath, int percent) {
						Log.i("bmob", "download-->onProgress :" + percent);
					}

					@Override
					public void onError(int statuscode, String errormsg) {
						Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
						Toast.makeText(MeActivity.this, "下载出错："+ statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
					}
				});

			}
		}

		// 点击 “保存” 的事件
		save.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				String newNickname = ((EditText)findViewById(R.id.me_change_username)).getText().toString();
				String newTag1 = ((EditText)findViewById(R.id.me_change_tag1)).getText().toString();
				String newTag2 = ((EditText)findViewById(R.id.me_change_tag2)).getText().toString();
				String newTag3 = ((EditText)findViewById(R.id.me_change_tag3)).getText().toString();

				modifyInfo(newNickname, newTag1, newTag2, newTag3);
			}
		});

		// back button
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent in = new Intent();
				in.setClass(MeActivity.this,HomeActivity.class);
				startActivity(in);
				MeActivity.this.finish();
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.me, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void modifyInfo(final String newNickname, String newTag1, String newTag2, String newTag3) {
		BmobUser currentUser = BmobUser.getCurrentUser(MeActivity.this);
		final String id = currentUser.getObjectId();

		if(newNickname.length() > 12){
			Toast.makeText(MeActivity.this, "用户昵称过长，请限制在12个字符以内", Toast.LENGTH_SHORT).show();
			return ;
		}

		if (currentUser != null) {
			final User newUser = new User();
			// 如果对应字段不为空值才进行更新,否则赋成原来的值
			if (newNickname != null && newNickname.equals("") == false)
				newUser.setNickname(newNickname);

			if (newTag1 != null && newTag1.equals("") == false)
				newUser.setTag1(newTag1);

			if (newTag2 != null && newTag2.equals("") == false)
				newUser.setTag2(newTag2);

			if (newTag3 != null && newTag3.equals("") == false)
				newUser.setTag3(newTag3);

			if (fileName != null) {
				File file = new File(fileName);
				if (!file.exists()) Log.e("bmob", "头像未更新");

			}

			BmobProFile.getInstance(MeActivity.this).upload(fileName, new UploadListener() {
				@Override
				public void onSuccess(String fileName, String url, BmobFile file) {
					Log.i("bmob", "文件上传成功：" + fileName + ",可访问的文件地址：" + file.getUrl());
					// fileName ：文件名（带后缀），这个文件名是唯一的，开发者需要记录下该文件名，方便后续下载或者进行缩略图的处理
					// url ：文件地址
					// file : BmobFile文件类型，`V3.4.1版本`开始提供，用于兼容新旧文件服务。
					// 注：若上传的是图片，url地址并不能直接在浏览器查看（会出现404错误），需要经过`URL签名`得到真正的可访问的URL地址,
					// 当然，`V3.4.1`的版本可直接从'file.getUrl()'中获得可访问的文件地址。
					newUser.setPicture(file);
					newUser.setPicFilename(fileName);
					newUser.update(MeActivity.this, id, new UpdateListener() {
						@Override
						public void onFailure(int arg0, String arg1) {
							Toast.makeText(MeActivity.this, "头像完善失败", Toast.LENGTH_SHORT).show();
						}

						@Override
						public void onSuccess() {
							Toast.makeText(MeActivity.this, "头像完善成功", Toast.LENGTH_SHORT).show();
							Intent intent = new Intent();
							intent.setClass(MeActivity.this, HomeActivity.class);
							startActivity(intent);
							MeActivity.this.finish();
						}
					});
				}

				@Override
				public void onProgress(int progress) {
					Log.i("bmob","onProgress :" + progress);
				}

				@Override
				public void onError(int statuscode, String errormsg) {
					Log.i("bmob","文件上传失败：" + errormsg);
				}
			});



			newUser.update(MeActivity.this, id , new UpdateListener() {

				@Override
				public void onFailure(int arg0, String arg1) {
					Toast.makeText(MeActivity.this, "完善失败！！！！", Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onSuccess() {
					Toast.makeText(MeActivity.this, "信息更新成功", Toast.LENGTH_SHORT).show();
					refreshActivitySponsorName(id.toString(),newNickname);
				}
			});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case 1:
				if (resultCode == RESULT_OK) {
					Uri uri = null;
					if (data != null && data.getData() != null)
						uri = data.getData(); // �ü�ͼƬ
					else if (photoUri != null)
						uri = photoUri;
					else {
						Toast.makeText(this, "OnActivityResult出错，case1", Toast.LENGTH_SHORT);
					}
					cropPhoto(uri); // �ü�ͼƬ
				}
				break;

			case 2:
				if (data != null) {
					Uri uri = data.getData();
					cropPhoto(uri); // �ü�ͼƬ
					Log.e("uri", uri.toString());
				} else {
					Log.i("bmob", "ͼƬ�����ڣ�");
					Toast.makeText(this, "OnActivityResult出错，case2", Toast.LENGTH_SHORT);
				}
				break;

			case 3:
				if (data != null) {
					Bundle extras = data.getExtras();
					Bitmap head = extras.getParcelable("data");
					if (head != null) {
						setPicToView(head);
						ImageView imageView = (ImageView) findViewById(R.id.me_portrait);
						imageView.setImageBitmap(head);
					}
				}
				break;

			case 4:
				Bundle bundle = data.getExtras();
				if (bundle != null) {
					TextView baseAddressTv = (TextView) this.findViewById(R.id.baseAddress);
					TextView detailAddressTv = (TextView) this.findViewById(R.id.detailAddress);
					baseAddressTv.setText(bundle.getString("baseAddress"));
					detailAddressTv.setText(bundle.getString("detailAddress"));
				}
			default:
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	// ����ϵͳ�ü�
	public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private void setPicToView(Bitmap mBitmap) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			return;
		}
		FileOutputStream b = null;
		String path = "/sdcard/Lets/myHead/";
		File file = new File(path);
		if (!file.exists())
			file.mkdirs(); // �����ļ���

		User curUser = BmobUser.getCurrentUser(this, User.class);
		fileName = path + curUser.getUsername() + "_head.jpg"; // ͼƬ����
		try {
			b = new FileOutputStream(fileName);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b); // ������д���ļ�
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i("bmob", e.getMessage());
		} finally {
			try { // �ر���
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onBackPressed() {
		// 这里处理逻辑代码，大家注意：该方法仅适用于2.0或更新版的sdk
		Intent backIntent = new Intent(MeActivity.this, HomeActivity.class);
		backIntent.setClass(MeActivity.this, HomeActivity.class);
//		startActivity(backIntent);
		finish();
	}

	public void refreshActivitySponsorName(String sponsorId, final String  newNickname){
		UserActivity ac = new UserActivity();
		ac.setSponsorName("newNickname");
		BmobQuery<UserActivity> query = new BmobQuery<UserActivity>();
		query.addWhereEqualTo("sponsorId", sponsorId);
		query.setLimit(15);

		query.findObjects(this, new FindListener<UserActivity>() {

			@Override
			public void onSuccess(List<UserActivity> object) {
				for (UserActivity activity : object) {
					String actiId = activity.getObjectId().toString();
					UserActivity ac = new UserActivity();
					ac.setSponsorName(newNickname);
					ac.update(MeActivity.this, actiId, new UpdateListener() {
						@Override
						public void onSuccess() {
							// TODO Auto-generated method stub
						}

						@Override
						public void onFailure(int code, String msg) {
							// TODO Auto-generated method stub
						}
					});
				}
			}
			@Override
			public void onError(int code, String msg) {
				Toast.makeText(MeActivity.this, "更新活动发起者昵称失败", Toast.LENGTH_SHORT).show();
			}
		});
	}
}
